import { ref } from 'vue'
import { ElMessage } from 'element-plus'

export interface ExportConfig {
  filename?: string
  sheetName?: string
  headers?: string[]
  fields?: string[]
  dateFormat?: string
  numberFormat?: string
}

export interface ExportData {
  [key: string]: any
}

export function useExport() {
  const isExporting = ref(false)

  // 导出为 CSV
  const exportToCSV = (
    data: ExportData[],
    config: ExportConfig = {}
  ) => {
    const {
      filename = 'export.csv',
      headers = [],
      fields = []
    } = config

    if (!data || data.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }

    isExporting.value = true

    try {
      // 如果没有指定字段，使用第一行数据的所有键
      const exportFields = fields.length > 0 ? fields : Object.keys(data[0])
      
      // 如果没有指定表头，使用字段名
      const exportHeaders = headers.length > 0 ? headers : exportFields

      // 构建 CSV 内容
      const csvContent = [
        // 表头
        exportHeaders.map(header => `"${header}"`).join(','),
        // 数据行
        ...data.map(row => 
          exportFields.map(field => {
            const value = row[field]
            return `"${formatCellValue(value, config)}"`
          }).join(',')
        )
      ].join('\n')

      // 添加 BOM 以支持中文
      const BOM = '\uFEFF'
      const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
      
      downloadFile(blob, filename.endsWith('.csv') ? filename : `${filename}.csv`)
      
      ElMessage.success('导出成功')
    } catch (error) {
      console.error('CSV 导出失败:', error)
      ElMessage.error('导出失败')
    } finally {
      isExporting.value = false
    }
  }

  // 导出为 JSON
  const exportToJSON = (
    data: ExportData[],
    config: ExportConfig = {}
  ) => {
    const { filename = 'export.json' } = config

    if (!data || data.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }

    isExporting.value = true

    try {
      const jsonContent = JSON.stringify(data, null, 2)
      const blob = new Blob([jsonContent], { type: 'application/json;charset=utf-8;' })
      
      downloadFile(blob, filename.endsWith('.json') ? filename : `${filename}.json`)
      
      ElMessage.success('导出成功')
    } catch (error) {
      console.error('JSON 导出失败:', error)
      ElMessage.error('导出失败')
    } finally {
      isExporting.value = false
    }
  }

  // 导出为 Excel (需要安装 xlsx 库)
  const exportToExcel = async (
    data: ExportData[],
    config: ExportConfig = {}
  ) => {
    const {
      filename = 'export.xlsx',
      sheetName = 'Sheet1',
      headers = [],
      fields = []
    } = config

    if (!data || data.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }

    isExporting.value = true

    try {
      // 动态导入 xlsx 库
      const XLSX = await import('xlsx')
      
      // 如果没有指定字段，使用第一行数据的所有键
      const exportFields = fields.length > 0 ? fields : Object.keys(data[0])
      
      // 如果没有指定表头，使用字段名
      const exportHeaders = headers.length > 0 ? headers : exportFields

      // 构建工作表数据
      const wsData = [
        exportHeaders,
        ...data.map(row => 
          exportFields.map(field => formatCellValue(row[field], config))
        )
      ]

      // 创建工作表
      const ws = XLSX.utils.aoa_to_sheet(wsData)
      
      // 设置列宽
      const colWidths = exportHeaders.map(() => ({ wch: 15 }))
      ws['!cols'] = colWidths

      // 创建工作簿
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, sheetName)

      // 导出文件
      XLSX.writeFile(wb, filename.endsWith('.xlsx') ? filename : `${filename}.xlsx`)
      
      ElMessage.success('导出成功')
    } catch (error) {
      console.error('Excel 导出失败:', error)
      ElMessage.error('导出失败，请确保已安装 xlsx 库')
    } finally {
      isExporting.value = false
    }
  }

  // 格式化单元格值
  const formatCellValue = (value: any, config: ExportConfig): string => {
    if (value === null || value === undefined) {
      return ''
    }

    // 日期格式化
    if (value instanceof Date) {
      return formatDate(value, config.dateFormat)
    }

    // 数字格式化
    if (typeof value === 'number') {
      return formatNumber(value, config.numberFormat)
    }

    // 布尔值转换
    if (typeof value === 'boolean') {
      return value ? '是' : '否'
    }

    // 对象转 JSON 字符串
    if (typeof value === 'object') {
      return JSON.stringify(value)
    }

    return String(value)
  }

  // 日期格式化
  const formatDate = (date: Date, format = 'YYYY-MM-DD HH:mm:ss'): string => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return format
      .replace('YYYY', String(year))
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hours)
      .replace('mm', minutes)
      .replace('ss', seconds)
  }

  // 数字格式化
  const formatNumber = (num: number, format?: string): string => {
    if (!format) return String(num)
    
    // 简单的数字格式化，可以根据需要扩展
    if (format === 'currency') {
      return `¥${num.toFixed(2)}`
    }
    
    if (format === 'percentage') {
      return `${(num * 100).toFixed(2)}%`
    }
    
    return String(num)
  }

  // 下载文件
  const downloadFile = (blob: Blob, filename: string) => {
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    link.style.display = 'none'
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    window.URL.revokeObjectURL(url)
  }

  // 批量导出（支持多种格式）
  const batchExport = async (
    data: ExportData[],
    formats: ('csv' | 'json' | 'excel')[],
    config: ExportConfig = {}
  ) => {
    const { filename = 'export' } = config
    
    for (const format of formats) {
      const formatConfig = {
        ...config,
        filename: `${filename}_${format}`
      }
      
      switch (format) {
        case 'csv':
          exportToCSV(data, formatConfig)
          break
        case 'json':
          exportToJSON(data, formatConfig)
          break
        case 'excel':
          await exportToExcel(data, formatConfig)
          break
      }
      
      // 添加延迟避免浏览器阻止多个下载
      if (formats.length > 1) {
        await new Promise(resolve => setTimeout(resolve, 500))
      }
    }
  }

  return {
    isExporting,
    exportToCSV,
    exportToJSON,
    exportToExcel,
    batchExport,
    formatCellValue,
    formatDate,
    formatNumber
  }
}